package com.example.weather1.controller;

import com.example.weather1.entity.UserEntity;
import com.example.weather1.mapper.UserMapper;
import com.example.weather1.utils.JWTUTIL;
import com.example.weather1.vo.JsonResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/front/user")
public class UserController {

    @Resource
    UserMapper userMapper;

    @GetMapping("/all")
    public JsonResult getLists(){
        List<UserEntity> all = userMapper.getAll();
        return JsonResult.success(all);
//        return all;
    }


//    注册
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody UserEntity user){

//        用户名不可重复
        UserEntity oneByname = userMapper.getOneByName(user.getWname());
        if(oneByname != null)
        {
            return JsonResult.failed("用户名重复");
        }

        boolean add = userMapper.add(user);

        if(add){
            return JsonResult.success(null);
        }

        return JsonResult.failed("注册失败");

    }


//    token管理 登录
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserEntity user){

//        用户名不可重复
        UserEntity oneByname = userMapper.login(user);
        if(oneByname == null)
        {
            return JsonResult.failed("用户名或密码不正确");
        }else {
            HashMap<String,String> payload = new HashMap<>();
            payload.put("phone", oneByname.getPhone().toString());
            payload.put("wname", oneByname.getWname());
            payload.put("phone",oneByname.getPhone());

            String token = JWTUTIL.jwt(user);
            payload.put("token", token);
            payload.put("exra","登录成功");

            System.out.println(payload);

            return  JsonResult.success(payload);
        }
    }

//    根据token修改用户信息
    @PostMapping("/edit")
    public JsonResult edit(@RequestHeader("token") String token,@RequestBody UserEntity user){

        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey("admin").parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String phone = claims.get("phone").toString();
        System.out.println(phone);

        user.setPhone(phone);

        boolean update = userMapper.update(user);

        if(update){
            return JsonResult.success(null);
        }

        return JsonResult.failed("修改失败");
    }
}
